<template>
  <div>
    <a-list-table
      :columns="columns"
      :tableData="listdata"
      :pagination="pagination"
      :isSelecttion="false"
      :loading="loading"
      :inputName="inputName"
      :scroll="{y:slotData.tableHeight}"
      tableId='detailTable'
      @onTableChange="handleTableChange"
      @onselectChange="onselectChange"
      @onAction="onAction"
      :links="links"
      @onTouchlinkCell="onTouchlinkCell"
      @onBlur="onBlur"
    >
    </a-list-table>
    <!-- <viewModal ref="viewModal" @ok="handleModalSaveOk" @close="handleModalCancel" /> -->
  </div>
</template>

<script>
import searchLayout from '@/views/app/biz/common/searchLayout'
import batchOperatBtn from '@/views/app/biz/common/batchOperatBtn'
import tableLayout from '@/views/app/biz/common/index'
import aListInfo from '@/views/app/biz/common/aListInfo'
import aListTable from '@/views/app/biz/common/aListTable'
import toDeliveryModal from './toDeliveryModal'
// import viewModal from './viewModal'
import {
  saveOederGoods,
  deleteInfo,
  deleteDetailInfo,
  getDetailByConditions,
  getDetailByConditionsCount,
} from './saleDelivery'
const columns = [
  {
    title: '配送单明细',
    children: [
      // { title: '采购单位名称', dataIndex: 'customerName', key: 'customerName', align: 'center' },
      // { title: '销售单号', dataIndex: 'saleOrderNo', key: 'saleOrderNo', align: 'center' },
      // { title: '配送单号', dataIndex: 'deliveryOrderNo', key: 'deliveryOrderNo', align: 'center' },
      { title: '商品编号', dataIndex: 'saleGoodsCode', key: 'saleGoodsCode', align: 'center' },
      { title: '品名', dataIndex: 'productNameZh', key: 'productNameZh', align: 'center' },
      // { title: '通用名', dataIndex: 'commonName', key: 'commonName', align: 'center' },
      // { title: '型号', dataIndex: 'model', key: 'model', align: 'center' },
      // { title: '规格', dataIndex: 'spec', key: 'spec', align: 'center' },
      { title: '生产厂家名称', dataIndex: 'manufacturerZh', key: 'manufacturerZh', align: 'center' },
      { title: '批号', dataIndex: 'batchCode', key: 'batchCode', align: 'center', width: '150px', scopedSlots: { customRender: 'batchCode' } },
      // { title: '效期', dataIndex: 'expiryDate', key: 'expiryDate', align: 'center' },
      { title: '配送数量', dataIndex: 'num', key: 'num', align: 'center', width: '100px', scopedSlots: { customRender: 'num' } },
      // { title: '单品含税价', dataIndex: 'iunitprice', key: 'iunitprice', align: 'center' },
      { title: '状态', dataIndex: 'deliveryState', key: 'deliveryState', align: 'center' },
      {
        title: '操作',
        dataIndex: 'action',
        key: 'operation',
        width: 120,
        align: 'center',
        scopedSlots: { customRender: 'action' }
      }
    ]
  }
]


let links = []

export default {
  components: {
    searchLayout,
    batchOperatBtn,
    tableLayout,
    aListInfo,
    aListTable,
    // viewModal, 
    toDeliveryModal
  },
  props: ['slotData', 'pid', 'loadDetail'],
  data () {
    return {
      columns: columns,
      listdata: [],
      keys: 1,
      inputName: ['batchCode', 'num'],
      links: links,
      loading: false,
      pagination: {
        //分页配置
        current: 1, //当前页码 current
        pageSize: 10, //每页显示条数 pageSize
        total: 1,
        showQuickJumper: true,
        showSizeChanger: true,
        pageSizeOptions: ['2', '10', '50', '100'],
        changeSize: false
      },
      beforChangePagination: {},
      // 查询表单
      q_formInfos: [
        { label: '销售单号', name: 'saleOrderNo', type: 'input', placeholder: '销售单号' },
        { label: '客户名称', name: 'customerName', type: 'customer', placeholder: '客户名称' },
        { label: ['查询', '重置'], type: 'botton' }
      ],
      // 查询表单绑定数据
      q_formDatas: {
        deliveryOrderPid: null
      },
      pData: {}, // 条件查询参数
      isJump: false,
      optText: '确认订单',
      selectedRowKeys: [],
      selectedRows: [],
      notAudit: false,
    }
  },
  computed: {},
  watch: {
    loadDetail (val) {
      console.log(this.pid);
      this.q_formDatas.deliveryOrderPid = this.pid
      this.getTotal()
      this.getList(this.q_formDatas)
    },
    //监听路由，只要路由有变化(路径，参数等变化)都有执行下面的函数，你可以
    $route: {
      handler: function (val, oldVal) {
        //created事件触发的函数可以在这里写... 
        console.log(this.$route);
        if (!this.$route.meta.keepAlive) {
          if (this.$route.meta.zhuangTai) {
            // this.q_formDatas.zhuangTai=this.$route.meta.zhuangTai
            this.q_formDatas.zhuangTai = null
          }
          this.getTotal()
          this.getList(this.q_formDatas)

        } else {//如果keepalive==true
          console.log(this.$route.params.isBack);
          if (!this.$route.params.isBack) {
            this.getTotal()
            this.getList(this.q_formDatas)
          }
          this.isJump = false
        }


      },
      deep: true,
      immediate: true
    }
  },
  beforeRouteLeave (to, from, next) {
    if (this.isJump) {
      from.meta.keepAlive = true
    } else {
      from.meta.keepAlive = false
    }
    next();
  },
  mounted () {
    // this.getTotal()
    // this.getList(this.q_formDatas)
  },
  methods: {
    // 触发改变页码,筛选,排序时的回调
    handleTableChange (pagination, filters, sorter) {
      this.pagination.current = pagination.current
      this.pagination.pageSize = pagination.pageSize
      this.getList(this.q_formDatas)
    },
    // 初始化页面时得到总数
    async getTotal () {
      let pages = ''
      pages = await getDetailByConditionsCount(this.q_formDatas)
      console.log(pages)
      if (pages && pages.code && pages.code === 'C1') {
        const pagination = { ...this.pagination }
        pagination.total = pages.data
        this.pagination = pagination
        console.log(this.pagination);
        this.pagination.showTotal = (showTotal) => { return `共 ${showTotal} 条` }
      }
    },
    // 初始化查询时的数据列表
    async getList (params) {
      console.log('请求列表时传入的数据', params)
      let actionBtn = ['添加', '删除']
      let noInput = false
      this.loading = true
      let listdata = []
      let res = ''
      //判断分页是否为标准分页
      if (this.pagination.changeSize) {
        this.pagination.changeSize = false
        this.pagination.pageSize = this.beforChangePagination.pageSize
      }
      res = await getDetailByConditions(params, this.pagination)
      this.loading = false
      console.log(res)
      if (res && res.code && res.code === 'C1' && res.data) {
        const resdata = res.data
        // const resdata=[{pid:'9321093801',saleOrderNo:'qqq'}]
        for (let item of resdata) {
          switch (item.deliveryState) {
            case '待收货':
              actionBtn = []
              noInput = true
              break
            default:
              actionBtn = ['添加', '删除']
              noInput = false

          }
          listdata.push({
            key: item.pid,
            btnKeys: '添加',
            btnTips: '点击添加该产品的其它批号',
            noInput: noInput,
            action: actionBtn,
            ...item
          }
          )
        }
        this.listdata = listdata
      } else {
        this.listdata = []
      }
      console.log(this.listdata)
    },
    // 新增按钮 点击了新增
    onAddData () {
      this.$refs.modal.addModal()
    },
    // 关闭模态详细框
    handleModalCancel () {
    },
    // 模态详细框提交按钮
    handleModalSaveOk () {
      this.getList(this.q_formDatas)
    },
    // 操作按钮
    onAction (text, record, index) {
      if (text == '添加') {
        // if(this.type=='modal'){

        //   return
        // }
        this.keys++
        let newRecord = JSON.parse(JSON.stringify(record))
        newRecord.action = ['移除']
        // newRecord.readyNum=null
        newRecord.pid = ''
        newRecord.sysSeq = 0
        newRecord.num = null
        newRecord.batchCode = null
        newRecord.key += '-' + this.keys
        //如果该页数据量大于等于pageSize，则pagination.pageSize++
        if (this.listdata.length >= this.pagination.pageSize) {
          this.beforChangePagination = JSON.parse(JSON.stringify(this.pagination))
          this.pagination.changeSize = true
          const pagination = { ...this.pagination }
          pagination.pageSize++
          this.pagination = pagination
        }
        let optInd = this.listdata.findIndex(item => {
          return item.key == record.key
        })
        this.listdata.splice(optInd + 1, 0, newRecord)
        this.listdata = this.listdata
        console.log(this.listdata);

        console.log(this.listdata);
      } else if (text == '移除') {
        let optInd = this.listdata.findIndex(item => {
          return item.key == record.key
        })
        this.listdata.splice(optInd, 1)
        //如果beforChangePagination小于pagination.pageSize，则pagination.pageSize--
        if (this.beforChangePagination.pageSize < this.pagination.pageSize) {
          console.log('1111');
          //保存分页配置
          // this.beforChangePagination=JSON.parse(JSON.stringify(this.pagination))
          // this.pagination.changeSize=true
          const pagination = { ...this.pagination }
          pagination.pageSize--
          this.pagination = pagination
        }
      } else if (text == '删除') {
        this.deleteObjInfo(record)
      }
    },
    onBlur (text, record, index, col) {
      if (!record.num) {
        this.$message.warning({ content: '配送数量不能为空', duration: 3 })
        return
      }
      if (!record.batchCode) {
        this.$message.warning({ content: '商品批号不能为空', duration: 3 })
        return
      }
      delete record.action
      this.saveObjInfo(record)
    },
    async deleteObjInfo (val) {
      let key = 'updatable'
      this.$message.loading({ content: '提交中', key, duration: 0 })
      let res = await deleteDetailInfo(val)
      if (res && res.code && res.code === 'C1' && res.data) {
        this.$message.success({ content: '删除成功', key, duration: 3 })
        this.getList(this.q_formDatas)
      } else {
        this.$message.error({ content: '删除失败,请稍后再试', key, duration: 3 })

      }
    },
    async saveObjInfo (val) {
      let data = []
      data.push(val)
      let key = 'updatable'
      this.$message.loading({ content: '提交中', key, duration: 0 })
      let res = await saveOederGoods(data)
      console.log(res)
      if (res && res.code && res.code === 'C1' && res.data) {
        this.$message.success({ content: '修改成功', key, duration: 3 })
        let changedIndex = this.listdata.findIndex(item => { return item.key == val.key })
        this.listdata[changedIndex] = res.data[0]
        this.listdata[changedIndex].key = res.data[0].pid
        this.listdata[changedIndex].action = ['添加', '删除']
        this.listdata = [...this.listdata]
        console.log(this.listdata);
      } else {
        this.$message.error({ content: '修改失败,请稍后再试', key, duration: 3 })
        this.getList(this.q_formDatas)
      }
    },

    // 查询按钮
    onFind () {
      this.pagination.current = 1
      this.getTotal()
      this.getList(this.q_formDatas)
    },

    onTouchlinkCell (text, record, index, link) {
      console.log(record);

    },
    // 多选批量操作
    onselectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
      for (const item of this.selectedRows) {
        if (item.action[0] != '确认') {
          this.notAudit = true
          return
        } else {
          this.notAudit = false
        }
      }
    },
    onDelectData () {
      if (this.selectedRows.length) {
        this.showDelConfirm(this.selectedRows)
      } else {
        this.$message.warning({ content: '未选择要删除的商品', duration: 3 })
      }
    },
    showDelConfirm (val, type) {
      let datas = []
      if (type == '1') {
        datas[0] = val
      } else {
        datas = val
      }
      const that = this;
      this.$confirm({
        title: '是否确认删除？',
        content: '删除后不可恢复！',
        onOk () {
          let reqArr = []
          let key = 'self'
          for (const item of datas) {
            reqArr.push(that.delOrder(item))
          }
          return Promise.all(reqArr).then(res => {
            console.log(res);
            for (const item of res) {
              console.log(item);
              if (item && item.code && item.code === 'C1' && item.data) {
                that.$message.success({ content: '采购订单' + item.data.saleOrderNo + '删除成功', duration: 3 })
              } else {
                that.$message.error({ content: '采购订单' + item.data.saleOrderNo + '删除失败，原因：' + item.message, duration: 3 })
              }
            }
            that.handleModalSaveOk()
          }).catch(err => {
            that.$message.error({ content: '操作出错:' + err, duration: 3 })
          })
        },
        onCancel () { },
      });
    },
    async delOrder (val) {
      let res = await deleteInfo(val)
      return res
    },
    onBatchAudit () {
      if (this.selectedRows.length) {
        if (this.notAudit) {
          this.$message.warning({ content: '已选项中含有已确认的记录，请选择未确认的记录', duration: 3 })
        } else {
          this.showConfirm(this.selectedRows)
        }
      } else {
        this.$message.warning({ content: '未选择要审核的记录', duration: 3 })
      }
    }
  },
}
</script>

<style>
</style>